 
    
   
    
    jquery-validation-railsのメモ書き。(Rails 5.1.4)
正規表現によるValidationです。
1. 郵便番号フィールドを記述
<div>郵便番号</div>
<div id=”emsg_postalcode”></div>
<div>
<%= form.text_field :postalcode, id: :postalcode, name: :postalcode, class: :text_field %>
</div>
2. Validatteをトリガーとするメソッドを記述
<script type=”text/javascript“>
$.validator.addMethod(“myregexp”, function(value, element, reg_str) {$.validator.addMethod(“myregexp”, function(value, element, reg_str) { var re = new RegExp(reg_str); return re.test(value);}, “入力値が正しくありません”);
$(function(){
  $(“#myform”).validate({
    rules : {
      “postalcode”: {
        myregexp: /^\d{3}[-]\d{2}$/
      },
    },
    messages: {
      “postalcode”: {
        myregexp: “ハイフン有り5桁で入力してください。”,
      },
    },
    errorPlacement: function(error, element) {
      if (element.attr(‘name’) == “postalcode”) {
        error.appendTo($(‘#emsg_postalcode’));
      }
    }
  });
});
</script>
以上
お問い合わせ
有限会社ロジックベースのお問い合わせ窓口はこちらです。